package com.iring.controller.pay;

import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iring.controller.BaseController;
import com.iring.domain.pay.check.PaypalCheck;
import com.iring.vo.pay.PaySuceessVO;


/**
 * paypal支付controller
 *
 * @author wanggan
 */
@Controller
@RequestMapping("/paypal")
public class PayPalController extends BaseController {

    /**
     * 这里用的是@SendToUser，这就是发送给单一客户端的标志
     */
    @SendToUser("/message")
    @ResponseBody
    public void handleSubscribe() {

    }

    @RequestMapping(value = "/cancel",method = RequestMethod.GET)
    public String payPalCancel()  {
//        return "redirect:"+payProperties.getDomain();
        logService.saveLog(getUserSession().getUsername(),"paypal cancel order",getUserRealIp(),true);
        return "redirect:"+ payProperties.getFailUrl();
    }

//    @RequestMapping(value = "/cancel",method = RequestMethod.GET)
//    public String payPalCancelPay(@RequestParam("token") String tradeNo)  {
//        System.out.println("token="+tradeNo);
//        orderService.cancelOrder(tradeNo,false);
////        return "redirect:"+payProperties.getDomain();
//        return "redirect:"+ payPalProperties.getCancelUrl();
//    }

    /**
     * paypal支付成功访问接口
     *
     * @param tradeNo
     *            交易单号
     * @param payerId
     *            支付用户id
     * @return 成功调往成功的url,失败跳往失败的链接
     */
    @RequestMapping(value = "/success", method = RequestMethod.GET)
    public String payPalSuccessPay(@RequestParam("token") String tradeNo,
                                   @RequestParam("PayerID") String payerId)  {
        PaypalCheck paypalCheck = new PaypalCheck();
        paypalCheck.setPayerId(payerId);
        paypalCheck.setTradeNo(tradeNo);

        paypalCheck = payReqService.checkPaypal(paypalCheck);
        if (paypalCheck.getPayResult()) {
            // websocket下发消息
            String orderid = paypalCheck.getOrderId();
            String username = paypalCheck.getUsername();
            Double restAmounts = paypalCheck.getRestAmounts();

            simpMessagingTemplate.convertAndSendToUser(orderid, "/message",
                    new PaySuceessVO(200, "支付成功", username, restAmounts));
            logService.saveLog(username,"paypal success notify",getUserRealIp(),true);
            return "redirect:"+payProperties.getSuccessUrl();
        }
        return "redirect:"+payProperties.getFailUrl();
    }
}
